// 主线程
import WasmRuntime from "./WasmRuntime.js";

let workerCount = 4;
const workers = [];
const taskSize = 1000;

export async function runParallel() {
  const memory = new WebAssembly.Memory({
    initial: 10,
    maximum: 100,
    shared: true,
  });
  const runtime = new WasmRuntime(memory);
  const wasm = await runtime.instantiate("./build/threads.wasm");
  // 初始化共享内存
  const sharedBuffer = wasm.instance.exports.memory.buffer;
  wasm.instance.exports.initSharedMemory(0, sharedBuffer.byteLength);

  // 创建工作线程
  for (let i = 0; i < workerCount; i++) {
    const worker = new Worker("wasm-worker.js", { type: "module" });
    worker.postMessage({
      memory: sharedBuffer,
      start: i * (taskSize / workerCount),
      end: (i + 1) * (taskSize / workerCount),
    });
    workers.push(worker);
  }

  // 收集结果
  let total = 0;
  workers.forEach((worker) => {
    worker.onmessage = (e) => {
      total += e.data;
      if (--workerCount === 0) {
        console.log("Total sum:", total);
      }
    };
  });
}
